<?php

class OrdersController extends Controller {

    public function init()
    {
        if (Yii::app()->user->isGuest){
            $this->redirect('/users/signin');
        }
        if (Yii::app()->request->isAjaxRequest) {
            $this->layout = false;
        }
        parent::init();
    }


    public function actionIndex()
    {
        $this->redirect("/orders/list");
    }

    public function actionAdd($id)
    {
        $templates = Templates::model()->findAll();
        if ($id){
            $products = Yii::app()->request->getPost('products', false);            
            $data = Yii::app()->request->getPost('data', false);
            $promo = Yii::app()->request->getPost('promo', false);
            $pickups = Yii::app()->request->getPost('pickup', false);
            if ($products){
                $order = new Orders();
                $order->user_id = Yii::app()->user->id;
                $order->template_id = $data['template_id'];
                $order->distributor_id = $data['store_id'];
                $order->date = date('Y-m-d H:i:s');
                $order->total = (float)$data['final'];
                $order->save();

                $promo_result = array();
                foreach ($promo as $p => $value){
                    $promo_result[(int)$p] = $value;
                }

                $pickups_result = array();
                foreach ($pickups as $pu => $value){
                    $pickups_result[(int)$pu] = $value;
                }

                foreach ($products as $id => $quantity){
                    $orderQ = new OrdersQuantity();
                    $orderQ->order_id = $order->id;
                    $orderQ->product_id = $id;
                    $orderQ->promo = $promo_result[$id];
                    $orderQ->pickup = $pickups_result[$id];
                    $orderQ->quantity = (int)$quantity;
                    $orderQ->save();
                }
                $this->redirect('/orders/view/'.$order->id);
            }else{
                $distributor = Distributors::model()->findByPk($id);                
                $this->render('add', array('templates' => $templates, 'distributor' => $distributor));
            }
        }else{
            $this->redirect('/orders/list');
        }
    }

    public function actionList()
    {
        $users = User::model()->sortById();
        $orders = Orders::model()->findAll();
        $this->render('list', array('orders' => $orders, 'users' => $users));
    }

    public function actionEdit($id)
    {
        $templates = Templates::model()->findAll();        
        if ($id){
            $order = Orders::model()->findByPk($id);
            $distributor = Distributors::model()->findByPk($order->distributor_id); 
            $dataProducts = TemplatesProducts::model()->findAllByAttributes(array('template_id' => $order->template_id));
            $result = array();
            foreach($dataProducts as $value){
                $result[]=$value['product_id'];
            }
            $sqlcategory = 'SELECT products_categories.* FROM products_categories INNER JOIN products ON products_categories.id = products.category_id
             WHERE products.id IN ('. implode(", ",$result). ') GROUP BY products_categories.id';
            $category = Yii::app()->db->createCommand($sqlcategory)->queryAll();
            $action = Yii::app()->request->getPost('action', false);
            $products = Yii::app()->request->getPost('products', false);
            $promo = Yii::app()->request->getPost('promo', false);
            $pickups = Yii::app()->request->getPost('pickup', false);
            $data = Yii::app()->request->getPost('data', false);
            
            if($action == 'edit_order'){
                $order->date = date('Y-m-d H:i:s');
                $order->total = (float)$data['final'];
                $order->save();
                
                $promo_result = array();
                foreach ($promo as $p => $value){
                    $promo_result[(int)$p] = $value;
                }

                $pickups_result = array();
                foreach ($pickups as $pu => $value){
                    $pickups_result[(int)$pu] = $value;
                }

                foreach ($products as $key => $quantity){
                    $query ="SELECT * FROM orders_quantity WHERE order_id = ".$id." AND product_id = ".$key;
                    $firstRecord = OrdersQuantity::model()->findBySql($query);
                    $orderQ = OrdersQuantity::model()->findByPk($firstRecord->id);
                    $orderQ->order_id = $id;
                    $orderQ->product_id = $key;
                    $orderQ->promo = $promo_result[$key];
                    $orderQ->pickup = $pickups_result[$key];
                    $orderQ->quantity = (int)$quantity;
                    $orderQ->save();     
                }
                $this->redirect('/orders/view/'.$id);
                
            }
            $this->render('edit', array(
                'order' => $order, 
                'distributor' => $distributor, 
                'templates'=> $templates, 
                'dataProducts'=>$dataProducts,
                'category'=>$category,
                'result'=>$result,
                 )
            );
        }else{
            $this->redirect('/orders/list');
        }
    }

    public function actionSubmit($id)
    {
        if ($id){
            $order = Orders::model()->findByPk($id);
            if ($order->status == 0){
                // Sending Emails with XLS files

            }else{

            }
            $this->render('edit', array('order' => $order));
        }else{
            $this->redirect('/orders/list');
        }
    }

    public function actionView($id)
    {
        if ($id){
            $order = Orders::model()->findByPk($id);
            if(isset($order)){
                $distributor = Distributors::model()->findByPk($order->distributor_id); 
                $orderQ = OrdersQuantity::model()->findAllByAttributes(array('order_id' => $id));
                $dataProducts = TemplatesProducts::model()->findAllByAttributes(array('template_id' => $order->template_id));
                $template = Templates::model()->findByPk($order->template_id);
                if(isset($template)){
                    $result = array();
                    foreach($dataProducts as $value){
                        $result[]=$value['product_id'];
                    }
                    if(count($result) > 0){
                        $sqlcategory = 'SELECT products_categories.* FROM products_categories left JOIN products ON products_categories.id = products.category_id
                         WHERE products.id IN ('. implode(", ",$result). ') GROUP BY products_categories.id';
                        
                        $category = Yii::app()->db->createCommand($sqlcategory)->queryAll();
                        if(isset($category)){
                            $isset_category = array();
                            foreach($category as $key){
                                $sql_tmp = 'SELECT * FROM products WHERE  category_id = '. $key['id'].' and id IN ('. implode(", ",$result). ')' ;
                                $product_description = Yii::app()->db->createCommand($sql_tmp)->queryAll(); 
                                foreach($product_description as $item){
                                    $order_quantity = OrdersQuantity::model()->findByAttributes(array('product_id'=>$item['id'],'order_id'=>$order->id)); 
                                    if(($order_quantity->quantity > 0 ) || ($order_quantity->promo > 0 ) || ($order_quantity->pickup > 0 )){
                                        if(!in_array($key['id'], $isset_category)){
                                            $isset_category[]=$key['id'];
                                        }
                                        
                                    }
                                }
                            }
                            $this->render('view', array(
                                'order' => $order,
                                'orderQ' => $orderQ, 
                                'distributor' => $distributor,
                                'result'=>$result,
                                'category'=>$category,
                                'template'=>$template,
                                'isset_category'=>$isset_category,
                                )
                            );
                        }else{
                            $this->redirect('/orders/list');
                        }
                    }else{
                        $this->redirect('/orders/list');
                    }
                }else{
                    $this->redirect('/orders/list');
                }
            }else{
                $this->redirect('/orders/list');
            }
        }else{
            $this->redirect('/orders/list');
        }
    }

    public function actionDelete($id)
    {
        $order = Orders::model()->findByPk($id);
       if (Yii::app()->user->role == 'admin' && $order){
            if (Yii::app()->request->isPostRequest){
                $orderQ = OrdersQuantity::model()->findAllByAttributes(array('order_id'=>$order->id));
                foreach($orderQ as $value){
                    $orderQ_tmp = OrdersQuantity::model()->findByPk($value->id);
                    $orderQ_tmp->delete();
                }
                $order->delete();
                $this->render('delete', array('success' => true, 'orders'=>$order));
                //$this->redirect('/distributors/view/'. $order->distributor_id);
            }else{
                 $this->render('delete', array());
            }
        }else{
            $this->redirect('/orders/list');
        }
    }
    public function actionAjax(){
        $template_id = Yii::app()->request->getPost('template_id', false);
        if ($template_id){
            $template = Templates::model()->findByPk($template_id);
            $template_products = TemplatesProducts::model()->findAllByAttributes(array('template_id' => $template_id));
            $result = array();
            foreach($template_products as $value){
                $result[]=$value['product_id'];
            }
            $sqlcategory = 'SELECT products_categories.* FROM products_categories INNER JOIN products ON products_categories.id = products.category_id
             WHERE products.id IN ('. implode(", ",$result). ') GROUP BY products_categories.id';
            $category = Yii::app()->db->createCommand($sqlcategory)->queryAll();
            $this->render('ajax', array('result'=>$result,'template_products' => $template_products, 'template' => $template, 'category'=>$category));
        }
    }
    
    public function actionSuccess($id){
        if ($id){
            $order = Orders::model()->findByPk($id);
            if($order){
				$data = Yii::app()->request->getPost('data', false);
				if(isset($data['delivered'])){
					$order->delivered = $data['delivered']; 
					$order->save();
				}
                $this->render('success', array('id' => $id));
            }else{
                $this->redirect('/orders/list');
            }
        }else{
            $this->redirect('/orders/list');
        }
    }
    
     public function actionSendmail($id){
        if ($id){
            $this->render('sendmail', array('id' => $id));
        }else{
            $this->redirect('/orders/list');
        }
    }
    
    public function actionAjaxEdit(){
        $template_id = Yii::app()->request->getPost('template_id', false);
        $order_id = Yii::app()->request->getPost('order_id', false);        
        if ($template_id){
            $template = Templates::model()->findByPk($template_id);
            $products = TemplatesProducts::model()->findAllByAttributes(array('template_id' => $template_id));
            $this->render('ajax', array('products' => $products, 'template' => $template));
        }
    }
    public function actionDowloadExecl($id){ 
		$data_post = Yii::app()->request->getPost('data', false);
		$vt_email = "info@vitadiet.com.au";
		//$api_email="info@vitadiet.com.au";
		//$vt_email = "it.langbat@gmail.com";
		//$api_email="it.langbat@gmail.com";
        if ($id){
            $data = '';
            $data_1 = '';
            $sqlorder = "SELECT * FROM orders WHERE id = ". $id;
            $order = Orders::model()->findBySql($sqlorder); 
            if(isset($order)){
                $user =  User::model()->findByPk($order->user_id);
                if(!isset($user)){
                    $user->username ="";
                }
                $sqlorderQ = "SELECT * FROM orders_quantity WHERE order_id = " . $order->id;
                $orderQ = OrdersQuantity::model()->findBySql($sqlorderQ);
                
                $sqldistributor = "SELECT * FROM distributors WHERE id = " . $order->distributor_id; 
                $distributor = Distributors::model()->findBySql($sqldistributor);
                
                $templateoder = "SELECT * FROM templates WHERE id = " . $order->template_id;
                $discount = Templates::model()->findBySql($templateoder);
                $settings = CJSON::decode($discount->settings);
				$minqties = CJSON::decode($discount->min_quantity);
                
                
                
                if(isset($distributor)){
                    $sqlsupplier =  "SELECT * FROM suppliers WHERE id = ". $distributor->supplier_id;
                    $supplier = Suppliers::model()->findBySql($sqlsupplier);
                    
                    $sqlstate = "SELECT * FROM states WHERE id = " . $distributor->state_id;
                    $state =  States::model()->findBySql($sqlstate);
                    
                    $sqlcompanies = "SELECT * FROM companies WHERE id =" . $distributor->company_id;
                    $companies =  Companies::model()->findBySql($sqlcompanies);
                /*SEND EMAIL WHEN PRESS "VT EMAIL ONLY"*/
                 if($data_post){
                    if($data_post['action'] == 1){
                       $data.= "<html xmlns:x=\"urn:schemas-microsoft-com:office:excel\">
                
                        <head>
                        <!--[if gte mso 9]><xml>
                        <x:ExcelWorkbook>
                        <x:ExcelWorksheets>
                        <x:ExcelWorksheet>
                        <x:Name>Application List</x:Name>
                        <x:WorksheetOptions>
                        <x:Print>
                        </x:Print>
                        </x:WorksheetOptions>
                        </x:ExcelWorksheet>
                        </x:ExcelWorksheets>
                        </x:ExcelWorkbook> 
                        </xml>
                        <![endif]--> 
                        </head>
                        <body>";
                        $delivered ='';
						if($order->delivered==1)
							$delivered ='Yes, Invoice Store Only';
						else
							$delivered ='No, Invoice Store & Send Order';
							
                        $header = "MEDICAL VITA DIET STORE ORDER";
                        
                        $data.= '<table width="100%" border="0" cellspacing="1" cellpadding="2" class="tbl_content">';
                        $data.= ' <tr class="head" valign="bottom">
                            <td colspan="5"><h3>'. $companies->title.' Store Order (Invoice Now)</h3></td>
                        </tr>'; 
                        $data.= ' <tr class="head" valign="bottom">
                                    <td align="left" width="10%" height="22"><b>Order No:</b></td>
                                    <td colspan="4" align="left" width="40%">'. $order->id .'</td>
                                </tr>'; 
        				$data.= ' <tr class="head" valign="bottom">
                                    <td align="left" width="10%" height="22"><b>Date:</b></td>
                                    <td colspan="4" align="left" width="40%">'. $order->date .'</td>
                                </tr>'; 
                        $data.= ' <tr class="head" valign="bottom">
                                    <td align="left" width="10%" height="22"><b>Supplier Name:</b></td>
                                    <td colspan="4" align="left" width="40%">Vita Tech Pty Ltd</td>
                                </tr>'; 
        				$data.= ' <tr class="head" valign="bottom">
                                    <td align="left" width="10%" height="22"><b>Supplier Code:</b></td>
                                    <td colspan="4" align="left" width="40%">56400</td>
                                </tr>'; 
        				$data.= ' <tr class="head" valign="bottom">
                                    <td align="left" width="10%" height="22"><b>Reps Name:</b></td>
                                    <td colspan="4" align="left" width="40%">'.$user->username .'</td>
                                </tr>';
								$data.= ' <tr class="head" valign="bottom">
                                    <td align="left" width="10%" height="22"><b>Rep Delievered Product Today?</b></td>
                                    <td colspan="4" align="left" width="40%">'. $delivered .'</td>
                                </tr>';
                         $data.= ' <tr class="head" valign="bottom">
                                    <td align="left" width="10%" height="22"></td>
                                    <td colspan="4" align="left" width="40%"></td>
                                </tr>';
                       $data.= ' <tr class="head" valign="bottom">
                                    <td align="left" width="10%" height="22"><b>STORE DETAILS</b></td>
                                    <td colspan="4" align="left" width="40%"></td>
                                </tr>'; 
        						  $data.= ' <tr class="head" valign="bottom">
                                    <td align="left" width="10%" height="22"><b>Store API No:</b></td>
                                    <td colspan="4" align="left" width="40%">#'.$distributor->api.'</td>
                                </tr>'; 
                        $data.= ' <tr class="head" valign="bottom">
                                    <td align="left" width="10%" height="22"><b>Store Name:</b></td>
                                    <td colspan="4" align="left" width="40%">'.$distributor->title.'</td>
                                </tr>'; 
                       
                        $data.= ' <tr class="head" valign="bottom">
                                    <td align="left" width="10%" height="22"><b>Address:</b></td>
                                    <td colspan="4" align="left" width="40%">'.$distributor->address.'</td>
                                </tr>';
                        $data.= ' <tr class="head" valign="bottom">
                                    <td align="left" width="10%" height="22"><b>Address 2: </b></td>
                                    <td colspan="4" align="left" width="40%">'.$distributor->address2.'</td>
                                </tr>'; 
                        $data.= ' <tr class="head" valign="bottom">
                                    <td align="left" width="10%" height="22"><b>Suburb: </b></td>
                                    <td colspan="4" align="left" width="40%">'. $distributor->city .'</td>
                                </tr>'; 
                        $data.= ' <tr class="head" valign="bottom">
                                    <td align="left" width="10%" height="22"><b>State: </b></td>
                                    <td colspan="4" align="left" width="40%">'.$state->title.'</td>
                                </tr>';
                        $data.= ' <tr class="head" valign="bottom">
                                    <td align="left" width="10%" height="22"><b>Postcode: </b></td>
                                    <td colspan="4" align="left" width="40%">'.$distributor->zip.'</td>
                                </tr>';
  						$data.= ' <tr class="head" valign="bottom">
                                    <td align="left" width="10%" height="22"><b>Phone: </b></td>
                                    <td colspan="4" align="left" width="40%">'.$distributor->phone.'</td>
                                </tr>';
                       
                        $data.= '</table>';
                        $data.= '<br>';
                        //Table detail
                        $data.= '<table width="100%" border="1" cellspacing="1" cellpadding="2" class="tbl_content">';
                        
                        $data.= ' <tr class="head" valign="bottom" bgcolor="#99FFFF" >
                                    <td align="center" width="10%" height="22" color="#0000FF">Api PDE</td>
                                    <td align="center" colspan="4" color="#0000FF">Product Description</td>
                                    <td align="center" width="16%" color="#0000FF">Base Price</td>
                                    <td align="center" width="12%" color="#0000FF">Purchase Qty</td>
                                    <td align="center" width="17%" color="#0000FF">Discount</td>
                                    <td align="center" width="14%" color="#0000FF">Vt Promo</td>
                                    <td align="center" width="8%" color="#0000FF">Stock Picked Up</td>
                                </tr>'; 
                        $sqlresult = "SELECT * FROM orders_quantity WHERE order_id = " . $order->id ;
                        $result = OrdersQuantity::model()->findAllBySql($sqlresult);
                        if(isset($result)){
                            foreach($result as $item) {
                                $sqlproduct = "SELECT * FROM products WHERE id = " . $item->product_id ;
                                $product = Products::model()->findBySql($sqlproduct);
								
								if(isset($minqties[$product->category_id][0])){
									if($item->quantity < $minqties[$product->category_id][0]){
										$discount_product = '';
									}else{
										if(isset($minqties[$product->category_id][1])){
											if($minqties[$product->category_id][0] <= $item->quantity && $item->quantity < $minqties[$product->category_id][1]){
												$discount_product = $settings[$product->category_id][0]/10 . "%";
											}else{
												$discount_product = $settings[$product->category_id][1]/10 . "%";
											}
										}else{
											$discount_product = $settings[$product->category_id][0]/10 . "%";
										}
									}
								}
								 
								
                                if($product->api_pde == 0){ $product->api_pde = '';}
                                if($item->quantity == 0){ $item->quantity = '';}
                                if($item->promo == 0 ){$item->promo ='';}
                                if($item->pickup ==0 ){$item->pickup = '';}
                                $data.= ' <tr class="head" valign="bottom">
                                            <td align="center" width="10%" height="22">'.$product->api_pde.'</td>
                                            <td align="left" colspan="4">'.$product->title.'</td>
                                            <td align="center" width="16%" >'.$product->price.'</td>
                                            <td align="center" width="12%">'.$item->quantity.'</td>
                                            <td align="center" width="17%">'.$discount_product.'</td>
                                            <td align="center" width="14%">'.$item->promo.'</td>
                                            <td align="center" width="8%">'.$item->pickup.'</td>
                                        </tr>';
                            }
                        }                 
                        
                        $data.= '</table></body></html>';
                        
                        $file=  'Vita_Tech_Order_Form_';
                        $tmp_file = $file . $order->id.'_'.time(). ".xls";
                        file_put_contents($_SERVER['DOCUMENT_ROOT'].'/public/'. $tmp_file ,$data);
                        
                        $order->xls = $tmp_file; 
                        $order->save();
						
						
						//TEST SEND ATTACHMENTS
						
						$title_email = "New ". $distributor->title ." ". $companies->title . " Order";
						
						$attachment = chunk_split(base64_encode(file_get_contents($_SERVER['DOCUMENT_ROOT'].'/public/'. $tmp_file)));
						 
						// a random hash will be necessary to send mixed content
						$separator = md5(time());

						// carriage return type (we use a PHP end of line constant)
						$eol = PHP_EOL;
						//$message = "<a href='http://rms.vitadiet.com.au/public/".$tmp_file."'>New ". $companies->title ." order - Click to Download.</a>".$eol;
						$message= "";
                        $tmp_ms = $data_post['description']; 
                        $first = explode( ".", $tmp_ms);
                        foreach($first as $value){
                            $message .= $value . $eol;
                        }
                        $message.=  $user->fname . ' ' . $user->lname . $eol;
						$message.=  $user->phone . $eol;
                        $message.=  $companies->title ." Representative";
						
						// main header (multipart mandatory)
						$headers = "From: ".$user->fname." ".$user->lname." <info@vitadiet.com.au>" . $eol;
						$headers .= "MIME-Version: 1.0" . $eol;
						$headers .= "Content-Type: multipart/mixed; boundary=\"" . $separator . "\"" . $eol . $eol;
						$headers .= "Content-Transfer-Encoding: 7bit" . $eol;
						$headers .= "This is a MIME encoded message." . $eol . $eol;

						// message
						$headers .= "--" . $separator . $eol;
						$headers .= "Content-Type: text/plain; charset=\"iso-8859-1\"" . $eol;
						$headers .= "Content-Transfer-Encoding: 8bit" . $eol . $eol;
						$headers .= $message . $eol . $eol;

						// attachment
						$headers .= "--" . $separator . $eol;
						$headers .= "Content-Type: application/octet-stream; name=\"" . $tmp_file . "\"" . $eol;
						$headers .= "Content-Transfer-Encoding: base64" . $eol;
						$headers .= "Content-Disposition: attachment" . $eol . $eol;
						$headers .= $attachment . $eol . $eol;
						$headers .= "--" . $separator . "--";

						
						// SEND EMAIL TO VT EMAIL
						mail($vt_email, $title_email, $message, $headers);
						
						//SEND EMAIL TO STORE
						if(isset($data_post['email_store'])){
							$email_distributor = $distributor->email;
							if(!empty($email_distributor)){
								mail($email_distributor, $title_email, $message, $headers);
							}
						}
						
                        $this->redirect('/distributors/view/'.$distributor->id );
                        
                    }else{
						/*SEND EMAIL WHEN PRESS "EMAIL VT AND API"*/
						
                        /*SEND TV EMAIL*/
                        $data.= "<html xmlns:x=\"urn:schemas-microsoft-com:office:excel\">
                
                        <head>
                        <!--[if gte mso 9]><xml>
                        <x:ExcelWorkbook>
                        <x:ExcelWorksheets>
                        <x:ExcelWorksheet>
                        <x:Name>Application List</x:Name>
                        <x:WorksheetOptions>
                        <x:Print>
                        </x:Print>
                        </x:WorksheetOptions>
                        </x:ExcelWorksheet>
                        </x:ExcelWorksheets>
                        </x:ExcelWorkbook> 
                        </xml>
                        <![endif]--> 
                        </head>
                        <body>";
                        
                        $header = "MEDICAL VITA DIET STORE ORDER";
                        
                        $data.= '<table width="100%" border="0" cellspacing="1" cellpadding="2" class="tbl_content">';
                        $data.= ' <tr class="head" valign="bottom">
                            <td colspan="5"><h3>'. $companies->title.' Store Order - API will send this order</h3></td>
                        </tr>'; 
                        $data.= ' <tr class="head" valign="bottom">
                                    <td align="left" width="10%" height="22"><b>Order No:</b></td>
                                    <td colspan="4" align="left" width="40%">'. $order->id .'</td>
                                </tr>'; 
        				$data.= ' <tr class="head" valign="bottom">
                                    <td align="left" width="10%" height="22"><b>Date:</b></td>
                                    <td colspan="4"align="left" width="40%">'. $order->date .'</td>
                                </tr>'; 
                        $data.= ' <tr class="head" valign="bottom">
                                    <td align="left" width="10%" height="22"><b>Supplier Name:</b></td>
                                    <td colspan="4" align="left" width="40%">Vita Tech Pty Ltd</td>
                                </tr>'; 
        				$data.= ' <tr class="head" valign="bottom">
                                    <td align="left" width="10%" height="22"><b>Supplier Code:</b></td>
                                    <td colspan="4" align="left" width="40%">56400</td>
                                </tr>'; 
        				$data.= ' <tr class="head" valign="bottom">
                                    <td align="left" width="10%" height="22"><b>Reps Name:</b></td>
                                    <td colspan="4" align="left" width="40%">'. $user->username.'</td>
                                </tr>';
                         $data.= ' <tr class="head" valign="bottom">
                                    <td align="left" width="10%" height="22"></td>
                                    <td colspan="4" align="left" width="40%"></td>
                                </tr>';
                       $data.= ' <tr class="head" valign="bottom">
                                    <td align="left" width="10%" height="22"><b>STORE DETAILS</b></td>
                                    <td colspan="4" align="left" width="40%"></td>
                                </tr>'; 
        						  $data.= ' <tr class="head" valign="bottom">
                                    <td align="left" width="10%" height="22"><b>Store API No:</b></td>
                                    <td colspan="4" align="left" width="40%">#'.$distributor->api.'</td>
                                </tr>'; 
                        $data.= ' <tr class="head" valign="bottom">
                                    <td align="left" width="10%" height="22"><b>Store Name:</b></td>
                                    <td colspan="4" align="left" width="40%">'.$distributor->title.'</td>
                                </tr>'; 
                       
                        $data.= ' <tr class="head" valign="bottom">
                                    <td align="left" width="10%" height="22"><b>Address:</b></td>
                                    <td colspan="4" align="left" width="40%">'.$distributor->address.'</td>
                                </tr>';
                        $data.= ' <tr class="head" valign="bottom">
                                    <td align="left" width="10%" height="22"><b>Address 2: </b></td>
                                    <td colspan="4" align="left" width="40%">'.$distributor->address2.'</td>
                                </tr>'; 
                        $data.= ' <tr class="head" valign="bottom">
                                    <td align="left" width="10%" height="22"><b>Suburb: </b></td>
                                    <td colspan="4" align="left" width="40%">'. $distributor->city .'</td>
                                </tr>'; 
                        $data.= ' <tr class="head" valign="bottom">
                                    <td align="left" width="10%" height="22"><b>State: </b></td>
                                    <td colspan="4" align="left" width="40%">'.$state->title.'</td>
                                </tr>';
                        $data.= ' <tr class="head" valign="bottom">
                                    <td align="left" width="10%" height="22"><b>Postcode: </b></td>
                                    <td colspan="4" align="left" width="40%">'.$distributor->zip.'</td>
                                </tr>';
  						$data.= ' <tr class="head" valign="bottom">
                                    <td align="left" width="10%" height="22"><b>Phone: </b></td>
                                    <td colspan="4" align="left" width="40%">'.$distributor->phone.'</td>
                                </tr>';
                        
                        $data.= '</table>';
                        $data.= '<br>';
                        //Table detail
                        $data.= '<table width="100%" border="1" cellspacing="1" cellpadding="2" class="tbl_content">';
                        
                        $data.= ' <tr class="head" valign="bottom" bgcolor="#99FFFF" >
                                    <td align="center" width="10%" height="22" color="#0000FF">Api PDE</td>
                                    <td align="center" colspan="4" color="#0000FF">Product Description</td>
                                    <td align="center" width="16%" color="#0000FF">Base Price</td>
                                    <td align="center" width="12%" color="#0000FF">Purchase Qty</td>
                                    <td align="center" width="17%" color="#0000FF">Discount</td>
                                    <td align="center" width="14%" color="#0000FF">Vt Promo</td>
                                    <td align="center" width="8%" color="#0000FF">Stock Picked Up</td>
                                </tr>'; 
                        $sqlresult = "SELECT * FROM orders_quantity WHERE order_id = " . $order->id ;
                        $result = OrdersQuantity::model()->findAllBySql($sqlresult);
                        if(isset($result)){
                            foreach($result as $item) {
                                $sqlproduct = "SELECT * FROM products WHERE id = " . $item->product_id ;
                                $product = Products::model()->findBySql($sqlproduct);
                                
								if(isset($minqties[$product->category_id][0])){
									if($item->quantity < $minqties[$product->category_id][0]){
										$discount_product = '';
									}else{
										if(isset($minqties[$product->category_id][1])){
											if($minqties[$product->category_id][0] <= $item->quantity && $item->quantity < $minqties[$product->category_id][1]){
												$discount_product = $settings[$product->category_id][0]/10 . "%";
											}else{
												$discount_product = $settings[$product->category_id][1]/10 . "%";
											}
										}else{
											$discount_product = $settings[$product->category_id][0]/10 . "%";
										}
									}
								}
								
                                if($product->api_pde == 0){ $product->api_pde = '';}
                                if($item->quantity == 0){ $item->quantity = '';}
                                if($item->promo == 0 ){$item->promo ='';}
                                if($item->pickup ==0 ){$item->pickup = '';}
                                $data.= ' <tr class="head" valign="bottom">
                                            <td align="center" width="10%" height="22">'.$product->api_pde.'</td>
                                            <td align="left" colspan="4">'.$product->title.'</td>
                                            <td align="center" width="16%" >'.$product->price.'</td>
                                            <td align="center" width="12%">'.$item->quantity.'</td>
                                            <td align="center" width="17%">'.$discount_product.'</td>
                                            <td align="center" width="14%">'.$item->promo.'</td>
                                            <td align="center" width="8%">'.$item->pickup.'</td>
                                        </tr>';
                            }
                        }                 
                        
                        $data.= '</table></body></html>';
                        
                        $file=  'Vita_Tech_Order_Form_';
                        $tmp_file = $file . $order->id.'_'.time(). ".xls";
                        file_put_contents($_SERVER['DOCUMENT_ROOT'].'/public/'. $tmp_file ,$data);
                        
                        $order->xls = $tmp_file; 
                        $order->save(); 
						
                        
                        
                        
						//TEST SEND ATTACHMENTS
			$title_email = "New ". $distributor->title ." ". $companies->title . " Order has been sent to API";
						
						$attachment = chunk_split(base64_encode(file_get_contents($_SERVER['DOCUMENT_ROOT'].'/public/'. $tmp_file)));
						 
						// a random hash will be necessary to send mixed content
						$separator = md5(time());

						// carriage return type (we use a PHP end of line constant)
						$eol = PHP_EOL;
						//$message = "<a href='http://rms.vitadiet.com.au/public/".$tmp_file."'>New ". $companies->title ." order - Click to Download.</a>".$eol;
						$message= "";
                        $tmp_ms = $data_post['description']; 
                        $first = explode( ".", $tmp_ms);
                        foreach($first as $value){
                            $message .= $value . $eol;
                        }
                        $message.=  $user->fname . ' ' . $user->lname . $eol;
						$message.=  $user->phone . $eol;
                        $message.=  $companies->title ." Representative";
						
						// main header (multipart mandatory)
						$headers = "From: ".$user->fname." ".$user->lname." <info@vitadiet.com.au>" . $eol;
						$headers .= "MIME-Version: 1.0" . $eol;
						$headers .= "Content-Type: multipart/mixed; boundary=\"" . $separator . "\"" . $eol . $eol;
						$headers .= "Content-Transfer-Encoding: 7bit" . $eol;
						$headers .= "This is a MIME encoded message." . $eol . $eol;

						// message
						$headers .= "--" . $separator . $eol;
						$headers .= "Content-Type: text/plain; charset=\"iso-8859-1\"" . $eol;
						$headers .= "Content-Transfer-Encoding: 8bit" . $eol . $eol;
						$headers .= $message . $eol . $eol;

						// attachment
						$headers .= "--" . $separator . $eol;
						$headers .= "Content-Type: application/octet-stream; name=\"" . $tmp_file . "\"" . $eol;
						$headers .= "Content-Transfer-Encoding: base64" . $eol;
						$headers .= "Content-Disposition: attachment" . $eol . $eol;
						$headers .= $attachment . $eol . $eol;
						$headers .= "--" . $separator . "--";
						
						
						//SEND EMAIL TO VT EMAIL
						mail($vt_email, $title_email, $message, $headers);
						
						//SEND EMAIL TO STORE
						if(isset($data_post['email_store'])){
							$email_distributor = $distributor->email;
							if(!empty($email_distributor)){
								mail($email_distributor, $title_email, $message, $headers);
							}
						}
						
                        /*SEND EMAIL API*/
                        
                        $data_1.= "<html xmlns:x=\"urn:schemas-microsoft-com:office:excel\">
                
                        <head>
                        <!--[if gte mso 9]><xml>
                        <x:ExcelWorkbook>
                        <x:ExcelWorksheets>
                        <x:ExcelWorksheet>
                        <x:Name>Application List</x:Name>
                        <x:WorksheetOptions>
                        <x:Print>
                        </x:Print>
                        </x:WorksheetOptions>
                        </x:ExcelWorksheet>
                        </x:ExcelWorksheets>
                        </x:ExcelWorkbook> 
                        </xml>
                        <![endif]--> 
                        </head>
                        <body>";
                        
                        $header1 = "VITA TECH P/L - API STORE ORDER";
                        
                        $data_1.= '<table width="100%" border="0" cellspacing="1" cellpadding="2" class="tbl_content">';
                        $data_1.= ' <tr class="head" valign="bottom">
                                    <td colspan="5"><h3>'. $header1 .'</h3></td>
                                </tr>'; 
                        $data_1.= ' <tr class="head" valign="bottom">
                                    <td align="left" width="10%" height="22"><b>Order No:</b></td>
                                    <td colspan="4" align="left" width="40%">'. $order->id .'</td>
                                </tr>'; 
        				$data_1.= ' <tr class="head" valign="bottom">
                                    <td align="left" width="10%" height="22"><b>Date:</b></td>
                                    <td colspan="4" align="left" width="40%">'. $order->date .'</td>
                                </tr>'; 
                        $data_1.= ' <tr class="head" valign="bottom">
                                    <td align="left" width="10%" height="22"><b>Supplier Name:</b></td>
                                    <td colspan="4" align="left" width="40%">Vita Tech Pty Ltd</td>
                                </tr>'; 
        				$data_1.= ' <tr class="head" valign="bottom">
                                    <td align="left" width="10%" height="22"><b>Supplier Code:</b></td>
                                    <td colspan="4" align="left" width="40%">56400</td>
                                </tr>'; 
        				
                         $data_1.= ' <tr class="head" valign="bottom">
                                    <td align="left" width="10%" height="22"></td>
                                    <td colspan="4" align="left" width="40%"></td>
                                </tr>';
                       $data_1.= ' <tr class="head" valign="bottom">
                                    <td align="left" width="10%" height="22"><b>STORE DETAILS</b></td>
                                    <td colspan="4" align="left" width="40%"></td>
                                </tr>'; 
        						  $data_1.= ' <tr class="head" valign="bottom">
                                    <td align="left" width="10%" height="22"><b>Store API No:</b></td>
                                    <td colspan="4" align="left" width="40%">#'.$distributor->api.'</td>
                                </tr>'; 
                        $data_1.= ' <tr class="head" valign="bottom">
                                    <td align="left" width="10%" height="22"><b>Store Name:</b></td>
                                    <td colspan="4" align="left" width="40%">'.$distributor->title.'</td>
                                </tr>'; 
                       
                        $data_1.= ' <tr class="head" valign="bottom">
                                    <td align="left" width="10%" height="22"><b>Address:</b></td>
                                    <td colspan="4" align="left" width="40%">'.$distributor->address.'</td>
                                </tr>';
                        $data_1.= ' <tr class="head" valign="bottom">
                                    <td align="left" width="10%" height="22"><b>Address 2: </b></td>
                                    <td colspan="4" align="left" width="40%">'.$distributor->address2.'</td>
                                </tr>'; 
                        $data_1.= ' <tr class="head" valign="bottom">
                                    <td align="left" width="10%" height="22"><b>Suburb: </b></td>
                                    <td colspan="4" align="left" width="40%">'. $distributor->city .'</td>
                                </tr>'; 
                        $data_1.= ' <tr class="head" valign="bottom">
                                    <td align="left" width="10%" height="22"><b>State: </b></td>
                                    <td colspan="4" align="left" width="40%">'.$state->title.'</td>
                                </tr>';
                        $data_1.= ' <tr class="head" valign="bottom">
                                    <td align="left" width="10%" height="22"><b>Postcode: </b></td>
                                    <td colspan="4" align="left" width="40%">'.$distributor->zip.'</td>
                                </tr>';
  						$data_1.= ' <tr class="head" valign="bottom">
                                    <td align="left" width="10%" height="22"><b>Phone: </b></td>
                                    <td colspan="4" align="left" width="40%">'.$distributor->phone.'</td>
                                </tr>';
                        $data_1.= '</table>';
                        $data_1.= '<br>';
                        //Table detail
                        $data_1.= '<table width="100%" border="1" cellspacing="1" cellpadding="2" class="tbl_content">';
                        
                        $data_1.= ' <tr class="head" valign="bottom" bgcolor="#99FFFF" >
                                    <td align="center" width="10%" height="22" color="#0000FF">Api PDE</td>
                                    <td align="center" colspan="4" color="#0000FF">Product Description</td>
                                    <td align="center" width="16%" color="#0000FF">Base Price</td>
                                    <td align="center" width="12%" color="#0000FF">Purchase Qty</td>
                                    
                                </tr>'; 
                        $sqlresult = "SELECT * FROM orders_quantity WHERE order_id = " . $order->id ;
                        $result = OrdersQuantity::model()->findAllBySql($sqlresult);
                        if(isset($result)){
                            foreach($result as $item) {
                                $sqlproduct = "SELECT * FROM products WHERE id = " . $item->product_id ;
                                $product = Products::model()->findBySql($sqlproduct);
                                 
                                if($product->api_pde == 0){ $product->api_pde = '';}
                                if($item->quantity == 0){ $item->quantity = '';}
                                if($item->promo == 0 ){$item->promo ='';}
                                if($item->pickup ==0 ){$item->pickup = '';}
                                $data_1.= ' <tr class="head" valign="bottom">
                                            <td align="center" width="10%" height="22">'.$product->api_pde.'</td>
                                            <td align="left" colspan="4">'.$product->title.'</td>
                                            <td align="center" width="16%" >'.$product->price.'</td>
                                            <td align="center" width="12%">'.$item->quantity.'</td>
                                           
                                        </tr>';
                            }
                        }                 
                        
                        $data_1.= '</table></body></html>';
                        
                        $api_file=  'API_Order_Form_';
                        $api_tmp_file = $api_file . $order->id.'_'.time(). ".xls";
                        file_put_contents($_SERVER['DOCUMENT_ROOT'].'/public/'. $api_tmp_file ,$data_1);
                        
                        $order->xls_api = $api_tmp_file; 
                        $order->save(); 
						
						//TEST SEND ATTACHMENTS
						$title_email = "New ". $distributor->title ." ". $companies->title . " Order";
						
						$attachment = chunk_split(base64_encode(file_get_contents($_SERVER['DOCUMENT_ROOT'].'/public/'. $api_tmp_file)));
						 
						// a random hash will be necessary to send mixed content
						$separator = md5(time());

						// carriage return type (we use a PHP end of line constant)
						$eol = PHP_EOL;
						//$message = "<a href='http://rms.vitadiet.com.au/public/".$tmp_file."'>New ". $companies->title ." order - Click to Download.</a>".$eol;
						$message= "";
                        $tmp_ms = $data_post['description']; 
                        $first = explode( ".", $tmp_ms);
                        foreach($first as $value){
                            $message .= $value . $eol;
                        }
                        $message.=  $user->fname . ' ' . $user->lname . $eol;
						$message.=  $user->phone . $eol;
                        $message.=  $companies->title ." Representative";
						
						// main header (multipart mandatory)
						$headers = "From: ".$user->fname." ".$user->lname." <info@vitadiet.com.au>" . $eol;
						$headers .= "MIME-Version: 1.0" . $eol;
						$headers .= "Content-Type: multipart/mixed; boundary=\"" . $separator . "\"" . $eol . $eol;
						$headers .= "Content-Transfer-Encoding: 7bit" . $eol;
						$headers .= "This is a MIME encoded message." . $eol . $eol;

						// message
						$headers .= "--" . $separator . $eol;
						$headers .= "Content-Type: text/plain; charset=\"iso-8859-1\"" . $eol;
						$headers .= "Content-Transfer-Encoding: 8bit" . $eol . $eol;
						$headers .= $message . $eol . $eol;

						// attachment
						$headers .= "--" . $separator . $eol;
						$headers .= "Content-Type: application/octet-stream; name=\"" . $api_tmp_file . "\"" . $eol;
						$headers .= "Content-Transfer-Encoding: base64" . $eol;
						$headers .= "Content-Disposition: attachment" . $eol . $eol;
						$headers .= $attachment . $eol . $eol;
						$headers .= "--" . $separator . "--";

						//mail($api_email, $title_email, $message, $headers);
						
						/*SEND EMAIL TO EARCH STATE OF STORE*/
						
						$sqlstates = "SELECT * FROM states WHERE id = (SELECT state_id FROM distributors WHERE id = ( SELECT distributor_id FROM orders WHERE id = ".$order->id.") ) ";
                        $states = States::model()->findBySql($sqlstates);
						if(isset($states->email)){
							/*SEND EMAIl TO EMAIL IN STATES*/
							$title_email = "New ". $distributor->title ." ". $companies->title . " Order";
							
							$state_email = $states->email;
							if(!empty($state_email)){
								mail($state_email, $title_email, $message, $headers);
							}
						}
						
						
                        $this->redirect('/distributors/view/'.$distributor->id );
                        
                    }
                }else{
                    $this->redirect(array('success','id'=>$id));
                }
        }else{
            $this->redirect('/orders/list');
        }
    }else{
        $this->redirect('/orders/list');
        }
    }else{
        $this->redirect('/orders/list');
    }
    }
    public function actionViewExcel($id, $opition ){
        if($id && $opition){
            $sqlorder = "SELECT * FROM orders WHERE id = ". $id;
            $order = Orders::model()->findBySql($sqlorder); 
            if(isset($order)){
                $user =  User::model()->findByPk($order->user_id);
                if(!isset($user)){
                    $user->username ="";
                }
                $sqlorderQ = "SELECT * FROM orders_quantity WHERE order_id = " . $order->id;
                $orderQ = OrdersQuantity::model()->findBySql($sqlorderQ);
                
                $sqldistributor = "SELECT * FROM distributors WHERE id = " . $order->distributor_id; 
                $distributor = Distributors::model()->findBySql($sqldistributor);
                
                $templateoder = "SELECT * FROM templates WHERE id = " . $order->template_id;
                $discount = Templates::model()->findBySql($templateoder);
                $settings = CJSON::decode($discount->settings);
                
                
                
                if(isset($distributor)){
                    $sqlsupplier =  "SELECT * FROM suppliers WHERE id = ". $distributor->supplier_id;
                    $supplier = Suppliers::model()->findBySql($sqlsupplier);
                    
                    $sqlstate = "SELECT * FROM states WHERE id = " . $distributor->state_id;
                    $state =  States::model()->findBySql($sqlstate);
                    
                    $sqlcompanies = "SELECT * FROM companies WHERE id =" . $distributor->company_id;
                    $companies =  Companies::model()->findBySql($sqlcompanies);
                    header("Content-Disposition: attachment; filename=orders.xls");
					

                    print "<html xmlns:x=\"urn:schemas-microsoft-com:office:excel\">";

                print "<html xmlns:x=\"urn:schemas-microsoft-com:office:excel\">
                
                <head>
                <!--[if gte mso 9]><xml>
                <x:ExcelWorkbook>
                <x:ExcelWorksheets>
                <x:ExcelWorksheet>
                <x:Name>Application List</x:Name>
                <x:WorksheetOptions>
                <x:Print>
                </x:Print>
                </x:WorksheetOptions>
                </x:ExcelWorksheet>
                </x:ExcelWorksheets>
                </x:ExcelWorkbook> 
                </xml>
                <![endif]--> 
                </head>
                <body>";
                
                print '<table width="100%" border="0" cellspacing="1" cellpadding="2" class="tbl_content">';
                print ' <tr class="head" valign="bottom">
                            <td colspan="5"><h3>'. $companies->title.' Store Order</h3></td>
                        </tr>'; 
                print ' <tr class="head" valign="bottom">
                            <td align="left" width="10%" height="22"><b>Order No:</b></td>
                            <td colspan="4" align="left" width="90%">'. $order->id .'</td>
                        </tr>'; 
				print ' <tr class="head" valign="bottom">
                            <td align="left" width="10%" height="22"><b>Date:</b></td>
                            <td colspan="4" align="left" width="90%">'. $order->date .'</td>
                        </tr>'; 
                print ' <tr class="head" valign="bottom">
                            <td align="left" width="10%" height="22"><b>Supplier Name:</b></td>
                            <td colspan="4" align="left" width="90%">Vita Tech Pty Ltd</td>
                        </tr>'; 
				print ' <tr class="head" valign="bottom">
                            <td align="left" width="10%" height="22"><b>Supplier Code:</b></td>
                            <td colspan="4" align="left" width="90%">56400</td>
                        </tr>'; 
                
                print ' <tr class="head" valign="bottom">
                            <td align="left" width="10%" height="22"></td>
                            <td colspan="4" align="left" width="90%"></td>
                        </tr>';
               print ' <tr class="head" valign="bottom">
                            <td align="left" width="10%" height="22"><b>STORE DETAILS</b></td>
                            <td colspan="4" align="left" width="90%"></td>
                        </tr>'; 
		      print ' <tr class="head" valign="bottom">
                            <td align="left" width="10%" height="22"><b>Store API No:</b></td>
                            <td colspan="4" align="left" width="90%">#'.$distributor->api.'</td>
                        </tr>'; 
                print ' <tr class="head" valign="bottom">
                            <td align="left" width="10%" height="22"><b>Store Name:</b></td>
                            <td colspan="4" align="left" width="90%">'.$distributor->title.'</td>
                        </tr>'; 
               
                print ' <tr class="head" valign="bottom">
                            <td align="left" width="10%" height="22"><b>Address:</b></td>
                            <td colspan="4" align="left" width="90%">'.$distributor->address.'</td>
                        </tr>';
                print ' <tr class="head" valign="bottom">
                            <td align="left" width="10%" height="22"><b>Address 2: </b></td>
                            <td colspan="4" align="left" width="90%">'.$distributor->address2.'</td>
                        </tr>'; 
                print '<tr class="head" valign="bottom">
                            <td align="left" width="10%" height="22"><b>Suburb: </b></td>
                            <td colspan="4" align="left" width="90%">'. $distributor->city .'</td>
                        </tr>'; 
                print ' <tr class="head" valign="bottom">
                            <td align="left" width="10%" height="22"><b>State: </b></td>
                            <td colspan="4" align="left" width="90%">'.$state->title.'</td>
                        </tr>';
                print ' <tr class="head" valign="bottom">
                            <td align="left" width="10%" height="22"><b>Postcode: </b></td>
                            <td colspan="4" align="left" width="90%">'.$distributor->zip.'</td>
                        </tr>';
				print '<tr class="head" valign="bottom">
                            <td align="left" width="10%" height="22"><b>Phone: </b></td>
                            <td colspan="4" align="left" width="90%">'.$distributor->phone.'</td>
                        </tr>';
                print '</table>';
                print '<br>';
                //Table detail
                print '<table width="100%" border="1" cellspacing="1" cellpadding="2" class="tbl_content">';
                
                if($opition == 2){
                    print ' <tr class="head" valign="bottom" bgcolor="#99FFFF" >
                            <td align="center" width="10%" height="22" color="#0000FF">Api PDE</td>
                            <td align="center" colspan="4" color="#0000FF">Product Description</td>
                            <td align="center" width="16%" color="#0000FF">Price 1</td>
                            <td align="center" width="12%" color="#0000FF">Purchase Qty</td>
                            
                        </tr>'; 
                    $sqlresult = "SELECT * FROM orders_quantity WHERE order_id = " . $order->id ;
                    $result = OrdersQuantity::model()->findAllBySql($sqlresult);
                    if(isset($result)){
                        foreach($result as $item) {
                            $sqlproduct = "SELECT * FROM products WHERE id = " . $item->product_id ;
                            $product = Products::model()->findBySql($sqlproduct);
                            if($item->quantity < 2){
                                $discount_product = '';
                            }elseif(($item->quantity > 1) && ($item->quantity < 6)){
                                $discount_product = $settings[$product->category_id][0]/10 . "%";
                            }else{
                                $discount_product = $settings[$product->category_id][1]/10 . "%";
                            }
                            if($product->api_pde == 0){ $product->api_pde = '';}
                          
                            if($item->promo == 0 ){$item->promo ='';}
                            if($item->pickup ==0 ){$item->pickup = '';}
                            print ' <tr class="head" valign="bottom">
                                        <td align="center" width="10%" height="22">'.$product->api_pde.'</td>
                                        <td colspan="4" align="left">'.$product->title.'</td>
                                        <td align="center" width="16%" >'.$product->price.'</td>
                                        <td align="center" width="12%">'.$item->quantity.'</td>
                                        
                                    </tr>';
                        }
                    }                 
                    print '</table></body></html>'; 
                }else{
                    print ' <tr class="head" valign="bottom" bgcolor="#99FFFF" >
                            <td align="center" width="10%" height="22" color="#0000FF">Api Pde</td>
                            <td align="center"  colspan="4" color="#0000FF">Product Description</td>
                            <td align="center" width="16%" color="#0000FF">Base Price</td>
                            <td align="center" width="12%" color="#0000FF">Purchase Qty</td>
                            <td align="center" width="17%" color="#0000FF">Discount</td>
                            <td align="center" width="14%" color="#0000FF">Vt Promo</td>
                            <td align="center" width="8%" color="#0000FF">Stock Picked Up</td>
                        </tr>'; 
                    $sqlresult = "SELECT * FROM orders_quantity WHERE order_id = " . $order->id ;
                    $result = OrdersQuantity::model()->findAllBySql($sqlresult);
                    if(isset($result)){
                        foreach($result as $item) {
                            $sqlproduct = "SELECT * FROM products WHERE id = " . $item->product_id ;
                            $product = Products::model()->findBySql($sqlproduct);
                            if($item->quantity < 2){
                                $discount_product = '';
                            }elseif(($item->quantity > 1) && ($item->quantity < 6)){
                                $discount_product = $settings[$product->category_id][0]/10 . "%";
                            }else{
                                $discount_product = $settings[$product->category_id][1]/10 . "%";
                            }
                            if($product->api_pde == 0){ $product->api_pde = '';}
                            if($item->quantity == 0){ $item->quantity = '';}
                            if($item->promo == 0 ){$item->promo ='';}
                            if($item->pickup ==0 ){$item->pickup = '';}
                            print ' <tr class="head" valign="bottom">
                                        <td align="center" width="10%" height="22">'.$product->api_pde.'</td>
                                        <td align="left" colspan="4">'.$product->title.'</td>
                                        <td align="center" width="16%" >'.$product->price.'</td>
                                        <td align="center" width="12%">'.$item->quantity.'</td>
                                        <td align="center" width="17%">'.$discount_product.'</td>
                                        <td align="center" width="14%">'.$item->promo.'</td>
                                        <td align="center" width="8%">'.$item->pickup.'</td>
                                    </tr>';
                        }
                    }                 
                    print '</table></body></html>'; 
                }
                    
        }else{
            $this->redirect('/orders/list');
        }
            }else{
                $this->redirect('/orders/list');
            }
        }else{
            $this->redirect('/orders/list');
        }
    }
}